import Cookies from 'js-cookie'

const USER_INFO = 'USER_INFO'

const TOKEN_KEY = 'TOKEN_KEY'

const LOCAL_STORAGE = window.localStorage

export function hasLocalStorage () {
  if (LOCAL_STORAGE) {
    return true
  } else {
    console.log('浏览器不支持localstorage')
    return false
  }
}

export function getToken () {
  if (!hasLocalStorage()) {
    return Cookies.get(TOKEN_KEY)
  } else {
    let token = LOCAL_STORAGE.getItem(TOKEN_KEY)
    if (token) {
      return JSON.parse(token)
    } else {
      return ''
    }
  }
}

export function setToken (token) {
  token = JSON.stringify(token)
  if (!hasLocalStorage()) {
    return Cookies.set(TOKEN_KEY, token)
  } else {
    console.log('ssssss')
    console.log(token)
    return LOCAL_STORAGE.setItem(TOKEN_KEY, token)
  }
}

export function removeToken () {
  if (!hasLocalStorage()) {
    return Cookies.remove(TOKEN_KEY)
  } else {
    return LOCAL_STORAGE.removeItem(TOKEN_KEY)
  }
}

export function setUserInfo (userInfo) {
  userInfo = JSON.stringify(userInfo)
  if (!hasLocalStorage()) {
    return Cookies.set(USER_INFO, userInfo)
  } else {
    console.log(userInfo)
    return LOCAL_STORAGE.setItem(USER_INFO, userInfo)
  }
}

export function getUserInfo () {
  if (!hasLocalStorage()) {
    let userInfo = Cookies.get(USER_INFO)
    if (userInfo) {
      return JSON.parse(userInfo)
    }
  } else {
    let userInfo = LOCAL_STORAGE.getItem(USER_INFO)
    console.log(userInfo)
    if (userInfo) {
      return JSON.parse(userInfo)
    }
  }
  return null
}

export function removeUserInfo () {
  if (!hasLocalStorage()) {
    return Cookies.remove(USER_INFO)
  } else {
    return LOCAL_STORAGE.removeItem(USER_INFO)
  }
}
